package com.gibs.peixunapi.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.gibs.peixunapi.VO.SubjectHubVO;
import com.gibs.peixunapi.VO.TestPaperVO;
import com.gibs.peixunapi.model.SubjectHub;
import com.gibs.peixunapi.utils.ConverterUtil;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import javax.persistence.EntityNotFoundException;
import javax.validation.Valid;

import org.springframework.transaction.annotation.Transactional;
import com.gibs.peixunapi.result.PageData;
import com.gibs.peixunapi.enums.ResultEnum;
import com.gibs.peixunapi.result.Result;
import com.gibs.peixunapi.utils.ResultUtil;
import com.gibs.peixunapi.dao.TestPaperDao;
import com.gibs.peixunapi.service.TestPaperService;
import com.gibs.peixunapi.model.TestPaper;

@Service
@Slf4j
public class TestPaperServiceImpl implements TestPaperService {

    @Autowired
    private TestPaperDao testPaperDao;

    @Transactional
    @Override
    public Result create(@Valid TestPaper object) {
        try {

//			objectDao.save(object);
            return ResultUtil.success(ResultEnum.CREATE_SUCCESS);
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResultUtil.error(ResultEnum.SERVER_ERROR);
        }
    }

    @Override
    public TestPaper copy(List<SubjectHubVO> subjectHubVOList, Integer testPaperId) {

        List<SubjectHub> subjectHubList = subjectHubVOList.stream().map(e -> {
            SubjectHub subjectHub = new SubjectHub();
            ConverterUtil.copyProperties(e, subjectHub);
            return subjectHub;
        }).collect(Collectors.toList());

        Map<String, Integer> subjectCountMap = new HashMap<>();
        int count = 0;
        /* 循环遍历转换为VO类 放入Map中返回结果*/
        for (int i = 0; i < subjectHubList.size(); i++) {
            count++;
            /*如果下一个type不同那么结束收集此类型完毕*/
            if (subjectHubList.get(i).getType() != null) {
                if (subjectHubList.get(i).getType().equals(subjectHubList.get(i + 1).getType())) {
                    subjectCountMap.put(subjectHubList.get(i).getType(), count);
                    count = 0;
                }
            }
        }
		//获取原有试卷题目信息
        TestPaper testPaper = testPaperDao.findById(testPaperId).orElseThrow(EntityNotFoundException::new);
        //设置新信息
        testPaper.setRadioCount(subjectCountMap.get("radio"));
        testPaper.setCheckCount(subjectCountMap.get("check"));
        testPaper.setJudgeCount(subjectCountMap.get("judge"));
        testPaper.setFillCount(subjectCountMap.get("fill"));
        testPaper.setQuestionCount(subjectCountMap.get("question"));
        testPaper.setId(null);
        //TODO 获取用户设置创建人
        TestPaper result = testPaperDao.saveAndFlush(testPaper);

        return result;
    }

    @Transactional
    @Override
    public Result save(@Valid TestPaper object) {
        try {

//			TestPaper testPaper = objectDao.findOne(object.getId());
//			ConverterUtil.copyNotNullProperties(object,testPaper);
//			objectDao.save(testPaper);
            return ResultUtil.success(ResultEnum.UPDATE_SUCCESS);
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResultUtil.error(ResultEnum.SERVER_ERROR);
        }
    }

    @Override
    public Result delete(Integer id) {
        try {
//			String[] ids = id.split(",");
//			for (String str : ids) {
//				objectDao.delete(Integer.valueOf(str));
//			}
            return ResultUtil.success(ResultEnum.DELETE_SUCCESS);
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResultUtil.error(ResultEnum.SERVER_ERROR);
        }
    }


    @Override
    public Result get(Integer id) {
        try {
//			HashMap<String, Object> data = new HashMap<String, Object>();
//			TestPaper object = objectDao.findOne(id);
//			if (object == null) {
//				Result(false, Status.FAILD, "查找失败", null);
//			}
//			HashMap<String,Object> map = new HashMap();
//			map.put("id", object.getId());
//			map.put("radioCount", object.getRadioCount()==null?"":object.getRadioCount());
//			map.put("radioScore", object.getRadioScore()==null?"":object.getRadioScore());
//			map.put("radioBak", object.getRadioBak()==null?"":object.getRadioBak());
//			map.put("checkCount", object.getCheckCount()==null?"":object.getCheckCount());
//			map.put("checkScore", object.getCheckScore()==null?"":object.getCheckScore());
//			map.put("checkBak", object.getCheckBak()==null?"":object.getCheckBak());
//			map.put("judgeCount", object.getJudgeCount()==null?"":object.getJudgeCount());
//			map.put("judgeScore", object.getJudgeScore()==null?"":object.getJudgeScore());
//			map.put("judgeBak", object.getJudgeBak()==null?"":object.getJudgeBak());
//			map.put("fillCount", object.getFillCount()==null?"":object.getFillCount());
//			map.put("fillScore", object.getFillScore()==null?"":object.getFillScore());
//			map.put("fillBak", object.getFillBak()==null?"":object.getFillBak());
//			map.put("questionCount", object.getQuestionCount()==null?"":object.getQuestionCount());
//			map.put("questionScore", object.getQuestionScore()==null?"":object.getQuestionScore());
//			map.put("questionBak", object.getQuestionBak()==null?"":object.getQuestionBak());
//			HashMap<String,Object> creatorId = new HashMap<String,Object>();
//			creatorId.put("name", object.getCreatorId()==null?"":object.getCreatorId().getName());
//			creatorId.put("id", object.getCreatorId()==null?"":object.getCreatorId().getId());
//			map.put("creatorId", creatorId);
//			data.put("object",map);

            return ResultUtil.success(ResultEnum.FIND_SUCCESS);
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResultUtil.error(ResultEnum.SERVER_ERROR);
        }
    }

    @Override
    public Result getList(String key) {
        try {
//			List<TestPaper> list = new ArrayList<>();
//			if (!StringUtils.isEmpty(key)) {
//				list = objectDao.findLike("%" + key + "%");
//			} else {
//				list = objectDao.findAll();
//			}
//			if (list.size() == 0) {
//				PageResult(true, Status.OK, "无数据", new ArrayList(), 0L,0,0);
//			}
//			List<Object> data = new ArrayList<>();
//			for(TestPaper object : list){
//				HashMap<String,Object> map = new HashMap();
//				map.put("id", object.getId());
//				map.put("radioCount", object.getRadioCount()==null?"":object.getRadioCount());
//				map.put("radioScore", object.getRadioScore()==null?"":object.getRadioScore());
//				map.put("radioBak", object.getRadioBak()==null?"":object.getRadioBak());
//				map.put("checkCount", object.getCheckCount()==null?"":object.getCheckCount());
//				map.put("checkScore", object.getCheckScore()==null?"":object.getCheckScore());
//				map.put("checkBak", object.getCheckBak()==null?"":object.getCheckBak());
//				map.put("judgeCount", object.getJudgeCount()==null?"":object.getJudgeCount());
//				map.put("judgeScore", object.getJudgeScore()==null?"":object.getJudgeScore());
//				map.put("judgeBak", object.getJudgeBak()==null?"":object.getJudgeBak());
//				map.put("fillCount", object.getFillCount()==null?"":object.getFillCount());
//				map.put("fillScore", object.getFillScore()==null?"":object.getFillScore());
//				map.put("fillBak", object.getFillBak()==null?"":object.getFillBak());
//				map.put("questionCount", object.getQuestionCount()==null?"":object.getQuestionCount());
//				map.put("questionScore", object.getQuestionScore()==null?"":object.getQuestionScore());
//				map.put("questionBak", object.getQuestionBak()==null?"":object.getQuestionBak());
//				HashMap<String,Object> creatorId = new HashMap<String,Object>();
//				creatorId.put("name", object.getCreatorId()==null?"":object.getCreatorId().getName());
//				creatorId.put("id", object.getCreatorId()==null?"":object.getCreatorId().getId());
//				map.put("creatorId", creatorId);
//				data.add(map);
//			}
            return ResultUtil.success(ResultEnum.FIND_SUCCESS);
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResultUtil.error(ResultEnum.SERVER_ERROR);
        }
    }

    @Override
    public Result getListPage(String key, Integer current, Integer limit) {
        try {
//			List<TestPaper> list = new ArrayList<>();
//			limit = limit == null ? 10 : limit;
//			current = current == null ? 1 : current;
//			int offset = (current - 1) * limit;
//			Long total = null;
//			if (!StringUtils.isEmpty(key)) {
//				list = objectDao.findPageLike("%" + key + "%", offset, limit);
//				total = objectDao.countLike("%" + key + "%");
//			} else {
//				list = objectDao.findPage(offset, limit);
//				total = objectDao.count();
//			}
//			if (total == 0) {
//				PageResult(true, Status.OK, "无数据", new ArrayList(), 0L,0,0);
//			}
//			List<Object> data = new ArrayList<>();
//			for(TestPaper object : list){
//				HashMap<String,Object> map = new HashMap();
//				map.put("id", object.getId());
//				map.put("radioCount", object.getRadioCount()==null?"":object.getRadioCount());
//				map.put("radioScore", object.getRadioScore()==null?"":object.getRadioScore());
//				map.put("radioBak", object.getRadioBak()==null?"":object.getRadioBak());
//				map.put("checkCount", object.getCheckCount()==null?"":object.getCheckCount());
//				map.put("checkScore", object.getCheckScore()==null?"":object.getCheckScore());
//				map.put("checkBak", object.getCheckBak()==null?"":object.getCheckBak());
//				map.put("judgeCount", object.getJudgeCount()==null?"":object.getJudgeCount());
//				map.put("judgeScore", object.getJudgeScore()==null?"":object.getJudgeScore());
//				map.put("judgeBak", object.getJudgeBak()==null?"":object.getJudgeBak());
//				map.put("fillCount", object.getFillCount()==null?"":object.getFillCount());
//				map.put("fillScore", object.getFillScore()==null?"":object.getFillScore());
//				map.put("fillBak", object.getFillBak()==null?"":object.getFillBak());
//				map.put("questionCount", object.getQuestionCount()==null?"":object.getQuestionCount());
//				map.put("questionScore", object.getQuestionScore()==null?"":object.getQuestionScore());
//				map.put("questionBak", object.getQuestionBak()==null?"":object.getQuestionBak());
//				HashMap<String,Object> creatorId = new HashMap<String,Object>();
//				creatorId.put("name", object.getCreatorId()==null?"":object.getCreatorId().getName());
//				creatorId.put("id", object.getCreatorId()==null?"":object.getCreatorId().getId());
//				map.put("creatorId", creatorId);
//				data.add(map);
//			}
//			PageData pageData = new PageData(total, limit, current);
            return ResultUtil.successPage(ResultEnum.SUCCESS);
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResultUtil.error(ResultEnum.SERVER_ERROR);
        }
    }


    @Override
    public Result getOptions(String key) {
        try {
//			List<TestPaper> list = new ArrayList<>();
//			if (!StringUtils.isEmpty(key)) {
//				list = objectDao.findLike("%" + key + "%");
//			} else {
//				list = objectDao.findAll();
//			}
//			List<Object> data = new ArrayList<>();
//			for (TestPaper object : list) {
//				HashMap<String, Object> map = new HashMap();
//				map.put("value", object.getId());
//				map.put("name", object.getRadioCount());
//				data.add(map);
//			}
            return ResultUtil.success(ResultEnum.SUCCESS);
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResultUtil.error(ResultEnum.SERVER_ERROR);
        }
    }

    @Override
    public Result getVOList(TestPaper testPaper, Map<String, List<SubjectHubVO>> subjectHubVOMap) {
        TestPaperVO testPaperVO = new TestPaperVO();
        ConverterUtil.copyProperties(testPaper, testPaperVO);
        for (Map.Entry<String, List<SubjectHubVO>> entry : subjectHubVOMap.entrySet()) {
            if ("radio".equals(entry.getKey())) {
                testPaperVO.setRadioList(entry.getValue());
            }
            if ("check".equals(entry.getKey())) {
                testPaperVO.setCheckList(entry.getValue());
            }
            if ("judge".equals(entry.getKey())) {
                testPaperVO.setJudgeList(entry.getValue());
            }
            if ("fill".equals(entry.getKey())) {
                testPaperVO.setFillList(entry.getValue());
            }
            if ("question".equals(entry.getKey())) {
                testPaperVO.setQuestionList(entry.getValue());
            }
        }
        return ResultUtil.success(ResultEnum.FIND_SUCCESS, testPaperVO);
    }


}

